const { ccclass, property } = cc._decorator;

@ccclass
export default class Loading extends cc.Component {
    @property(cc.ProgressBar)
    progressBar: cc.ProgressBar = null;
    @property(cc.Label)
    descProgress: cc.Label = null;

    res = ["gameHall"];
    statistics = {};//统计所有加载项进度
    static instance: Loading;
    start() {
        Loading.instance = this;
        cc.debug.setDisplayStats(false);
        this.preLoadRes();
    }

    preLoadRes() {
        this.res.forEach(name => {
            this.statistics[name] || (this.statistics[name] = { cpt: 0, total: 0 });
            let progressCb = (cpt, total) => {
                if (this.statistics) {
                    this.statistics[name].cpt = cpt;
                    this.statistics[name].total = total;
                    this.setProgress();
                }
            };
            let errorCb = err => {
                err && console.log(err);
            };
            if (name.indexOf("resources") > -1) {
                cc.loader.loadResDir("/", null, progressCb, errorCb);
            } else {
                cc.director.preloadScene(name, progressCb, errorCb);
            }
        })
    }

    setProgress() {
        let progress = 0;
        for (let name in this.statistics) {
            let obj = this.statistics[name];
            let pg = obj.cpt / obj.total / this.res.length;
            isNaN(pg) && (pg = 0);
            progress += pg;
        }
        if (progress >= 1) {
            cc.director.loadScene("gameHall");
            console.log("加载完成");
        } else {
            if (progress < this.progressBar.progress) return;
            this.progressBar.progress = progress;
            this.descProgress.string = Math.round(progress * 100) + "%";
        }
    }

}